import jpushIM from '@/js_sdk/jim.js'
import jimMsg from '@/utils/imMsgApi.js'


const USER_KEY = 'user';

const config = {
	// 极光IM appkey
	jimAppkey: '5fcedd501fd796368143d74e',
	jimMasterSecret: '4291d09fd67f47f7f9b2d691',
	jimLocalhost: 'https://fmedia.im.jiguang.cn/',
}


const state = {
	jimLoginInfo: null,
	hasLogin: null,
	jimUserInfo: {},
	isJimInit: false,
	syncConversation: [],
	conversation: [],
	chatList: [],
	singleInfo: {},
}

let number = 0;
let isConversation = false;
let isConverNumber = 0;

const actions = {
	jimInit(ctx) {
		jpushIM.init().then(res => {
			let inter = setInterval(() => {
				if (jpushIM.isInit() || number > 20) {
					clearInterval(inter);
					ctx.commit('jimInit', true);
				} else {
					number++;
				}
			}, 200)
		})
	},
	jimGetSingleInfo(ctx, data) {
		ctx.state.chatList = []
		if (data) {
			let params = {
				username: data
			};
			jpushIM.getUserInfo(params)
				.then(res => {
					if (res.code == 0) {
						let user = res && res.user_info || {
							username: data
						}
						ctx.dispatch('jimGetSingleMsg', user)
					}
				})
		}
	},
	jimResetUnreadCount(ctx, data) {
		let params = {
			username: data.username,
			appkey: data.appkey
		}
		jpushIM.resetUnreadCount(params)
		ctx.dispatch('jimUpdateConversation', data)
	},
	jimUpdateConversation(ctx, data) {
		let params = {
			username: data.username,
			appkey: data.appkey
		}
	
		jpushIM.updateConversation(params)
	},
	jimGetSingleMsg(ctx, user) {
		let chatList = jimMsg.getSingleMsg(ctx.state.conversation, ctx.state.syncConversation, user);
		ctx.commit('jimGetSingleMsg', chatList);
		ctx.commit('jimSetSingleInfo', user);
		ctx.dispatch('jimResetUnreadCount', user)
	},
	jimLoginOut(ctx) {
		return new Promise((resolve, reject) => {
			jpushIM.loginOut();
			ctx.commit('jimLoginOut');
			setTimeout(() => {
				if (!jpushIM.isInit()) {
					jpushIM.init()
				}
			}, 500)
		})
		
	},
	jimLogin(ctx, data) {
		
		uni.setStorageSync('jimLoginInfo', data);
		jpushIM.login(data).then(res => {
			ctx.commit('jimLogin');
			ctx.dispatch('jimGetUserInfo', data.username)
			ctx.dispatch('jimOnSyncConversation')
			ctx.dispatch('jimOnMsgReceive')
			ctx.dispatch('jimGetConversation')
			// uni.toast('登录成功')
		})
	},
	jimGetConversation(ctx) {
		jpushIM.getConversation().then(res => {
			if (res.code == 0) {
				let conversations = res.conversations || [];
				conversations.forEach(e => {
					e.avatar = e.avatar ? config.jimLocalhost + e.avatar : config.$defaultAvatar
				})
				ctx.dispatch('jimGetConversationFormat', conversations)
			}
		})
	},
	jimOnMsgReceive(ctx) {
		jpushIM.onMsgReceive(res => {
			let msgs = res.messages || [];
			if (msgs && msgs[0]) {
				let msg = jimMsg.formatMsgInfoReceive(msgs[0])
				ctx.commit('jimSendMsgAdd', msg)
				ctx.dispatch('jimGetConversation')
			}
		})
	},
	jimGetConversationFormat(ctx, data) {
		let conversation = jimMsg.formatConversation(data, ctx.state.syncConversation);
		ctx.commit('jimGetConversationFormat', conversation)
	},
	jimOnSyncConversation(ctx) {
		jpushIM.onSyncConversation().then(res => {
			ctx.commit('jimOnSyncConversation', res)
		})
	
	},
	jimRegister(ctx, data) {
		jpushIM.register(data).then(res => {
			console.log(res)
			util.toast('注册成功')
		})
	
	},
	jimGetUserInfo(ctx, data) {
		let params = {
			username: data
		}
		jpushIM.getUserInfo(params).then(res => {
			if (res.code == 0) {
				let user = res && res.user_info || {
					username: data
				}
				ctx.commit('jimGetUserInfo', user);
			}
		})
	},
	jimUpdateSelfInfo(ctx, data) {
		let params = data;
	
		jpushIM.updateSelfInfo(params).then(res => {
			console.log(res)
			if (res.code == 0) {
				ctx.dispatch('jimGetUserInfo', ctx.state.jimUserInfo.username)
			}
		})
	},
	jimUpdateSelfPwd(ctx, data) {
		let object = typeof data === 'object' ? JSON.parse(JSON.stringify(obj)) : obj;
		let params = data;
		jpushIM.updateSelfPwd(params).then(res => {
			if(res.code == 0){
				let jimLoginInfo = uni.setStorageSync('jimLoginInfo');
				if(jimLoginInfo.username){
					jimLoginInfo.password = object.new_pwd;
					uni.setStorageSync('jimLoginInfo', jimLoginInfo);
				}
			}
		})
	},
	jimSendSingleMsg(ctx, data) {
		let params = data;
		jpushIM.sendSingleMsg(params).then(res => {
			if (res.code == 0) {
				let jimUserInfo = ctx.state.jimUserInfo;
				let msgInfo = jimMsg.formatMsgInfo(jimUserInfo, params, res)
				ctx.commit('jimSendMsgAdd', msgInfo)
				if(!ctx.state.chatList.length){
					setTimeout(() => {
						ctx.dispatch('jimGetSingleInfo', data.target_username)
					}, 500)
				}
			}
		})
	},
	jimSendSinglePic(ctx, data) {
		let params = data;
		jpushIM.sendSinglePic(params).then(res => {
			console.log(res)
			if (res.code == 0) {
				let jimUserInfo = ctx.state.jimUserInfo;
				let msgInfo = jimMsg.formatMsgInfo(jimUserInfo, params, res)
				ctx.commit('jimSendMsgAdd', msgInfo)
				if(!ctx.state.chatList.length){
					setTimeout(() => {
						ctx.dispatch('jimGetSingleInfo', data.target_username)
					}, 500)
				}
			}
		})
	},
	jimSendSingleFile(ctx, data) {
		let params = data;
		jpushIM.sendSingleFile(params).then(res => {
			console.log(res)
			if (res.code == 0) {
				let jimUserInfo = ctx.state.jimUserInfo;
				let msgInfo = jimMsg.formatMsgInfo(jimUserInfo, params, res)
				ctx.commit('jimSendMsgAdd', msgInfo)
				if(!ctx.state.chatList.length){
					setTimeout(() => {
						ctx.dispatch('jimGetSingleInfo', data.target_username)
					}, 500)
				}
			}
		})
	},
	updateSelfAvatar(ctx, data) {
		let params = {
			avatar: data
		}
		jpushIM.updateSelfAvatar(params).then(res => {
			if(res.code == 0){
				ctx.dispatch('jimGetUserInfo', ctx.state.jimUserInfo.username)
			}
		})
	}
}


const mutations = {
	jimLogin(state, data){
		state.hasLogin = true;
	},
	jimInit(state, data){
		state.isJimInit = data;
	},
	jimLoginOut(state, data){
		state.hasLogin = false;
		state.jimUserInfo ={};
		state.isJimInit = false;
		state.syncConversation = [];
		state.conversation = [];
		state.chatList = [];
		state.singleInfo = {};
		uni.setStorageSync("jimLoginInfo", '');
	},
	jimGetUserInfo(state, data){
		state.jimUserInfo = data;
	},
	setHasLogin(state, data){
		state.hasLogin = data;
	},
	jimOnSyncConversation(state, data){
		if(Object.prototype.toString.call(data) === "[object Array]"){
			state.syncConversation = data;
		}else{
			state.syncConversation = [];
		}
	},
	jimGetConversation(state, data){
		if(Object.prototype.toString.call(data) === "[object Array]"){
			data.forEach(e => { e.content = '' })
			state.conversation = data;
		}else{
			state.conversation = [];
		}
	},
	jimGetSingleMsg(state, data){
		if(data.isfind){
			state.chatList = data._chatInfoList;
		}else{
			state.conversation.unshift(data._chatList);
			state.chatList = [];
		}
	},
	jimSetSingleInfo(state, data){
		state.singleInfo = data;
	},
	jimSendMsgAdd(state, data){
		let from_username = data.from_username;
		let appkey = data.from_appkey;
		let list = state.syncConversation.map(e => e.from_username);
		let index = list.indexOf(from_username)
		
		if(index != -1){
			state.syncConversation[index].msgs.push(data);
		}else{
			let syncConversation = {
				from_username: from_username,
				from_appkey: appkey,
				msg_type: 3,
				receipt_msgs: [],
				unread_msg_count: 0,
				msgs: [data]
			};
			state.syncConversation.push(syncConversation);
		}
		console.log(`state.syncConversation`, state.syncConversation)
	},
	jimGetConversationFormat(state, data){
		state.conversation = data;
	}
}

export default {
	mutations,
	state,
	actions
}